package com.liziyi0914.morearmor.effect;

import com.liziyi0914.morearmor.PlayerManager;
import com.liziyi0914.morearmor.Utils;
import com.liziyi0914.morearmor.armor.BaseArmor;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.EntityDamageEvent;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.player.HungerManager;
import net.minecraft.entity.player.PlayerEntity;
import net.minecraft.item.Items;
import net.minecraft.server.network.ServerPlayerEntity;
import net.minecraft.server.world.ServerWorld;

import java.util.function.Predicate;


public class HayBlockEffect extends AbstractEffect {

    @Listener
    public void onFall(EntityDamageEvent e) {
        if (!e.getSource().isFromFalling() || !predicateArmor().test(e.getEntity())) {
            return;
        }
        if (e.getEntity().getEntityWorld() instanceof ServerWorld) {
            e.setCanceled(true);
        }
    }

    @Listener
    public void onDamage(EntityDamageEvent e) {
        if (!e.getSource().isFire() || !predicateArmor().test(e.getEntity())) {
            return;
        }
        LivingEntity entity = e.getEntity();

        ((PlayerEntity) entity).getInventory().armor.forEach(itemStack -> {
            if (itemStack.getItem() instanceof BaseArmor armor) {
                if (armor.getItem().equals(Items.HAY_BLOCK)) {
                    itemStack.decrement(1);
                }
            }
        });
    }

    @Listener
    public void tick(WorldTickEvent e) {
        for (Entity entity : e.getWorld().getEntities()) {
            if (entity instanceof LivingEntity livingEntity) {
                if (!predicateArmor().test(livingEntity)) {
                    continue;
                }
                final ServerPlayerEntity playerEntity = PlayerManager.get(entity.getUuid());
                if (playerEntity == null) continue;
                HungerManager mgr = playerEntity.getHungerManager();
                if (mgr.isNotFull()) {
                    mgr.add(20, mgr.getFoodLevel());
                }
            }
        }
    }

    @Override
    public Predicate<LivingEntity> predicateArmor() {
        return Utils.hasItemArmor(Items.HAY_BLOCK);
    }
}
